package dj.common.support;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice(annotations = { HttpWrapperResponse.class })
public class HttpWrappedResponseBodyAdvice implements ResponseBodyAdvice {

	@Override
	public boolean supports(MethodParameter methodParameter, Class aClass) {
		return true;
	}

	@Override
	public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class aClass,
			ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
		try {
			if (body instanceof String) {
				serverHttpResponse.getHeaders()
						.setContentType(MediaType.parseMediaType(MediaType.APPLICATION_JSON_VALUE));
				ObjectMapper objectMapper = new ObjectMapper();
				return objectMapper.writeValueAsString(ResponseHandler.success(body));
			} else {
				return ResponseHandler.success(body);
			}
		} catch (Exception e) {
			return body;
		}
	}
}
